Ext.ns('Ext.ux.grid');
var wcbl;
/**
 * @class Ext.ux.grid.BufferView
 * @extends Ext.grid.GridView A custom GridView which renders rows on an
 *          as-needed basis. 自定义grid缓冲显示，用于数据条数较多时，快速显示
 */
Ext.ux.grid.BufferView = Ext.extend(Ext.grid.GridView, {
	/**
	 * @cfg {Number} rowHeight The height of a row in the grid.
	 */
	rowHeight : 19,

	/**
	 * @cfg {Number} borderHeight The combined height of border-top and
	 *      border-bottom of a row.
	 */
	borderHeight : 2,

	/**
	 * @cfg {Boolean/Number} scrollDelay The number of milliseconds before
	 *      rendering rows out of the visible viewing area. Defaults to 100.
	 *      Rows will render immediately with a config of false.
	 */
	scrollDelay : 100,

	/**
	 * @cfg {Number} cacheSize The number of rows to look forward and backwards
	 *      from the currently viewable area. The cache applies only to rows
	 *      that have been rendered already.
	 */
	cacheSize : 20,

	/**
	 * @cfg {Number} cleanDelay The number of milliseconds to buffer cleaning of
	 *      extra rows not in the cache.
	 */
	cleanDelay : 500,

	initTemplates : function() {
		Ext.ux.grid.BufferView.superclass.initTemplates.call(this);
		var ts = this.templates;
		// empty div to act as a place holder for a row
		ts.rowHolder = new Ext.Template('<div class="x-grid3-row {alt}" style="{tstyle}"></div>');
		ts.rowHolder.disableFormats = true;
		ts.rowHolder.compile();

		ts.rowBody = new Ext.Template(
				'<table class="x-grid3-row-table" border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
				'<tbody><tr>{cells}</tr>',
				(this.enableRowBody
						? '<tr class="x-grid3-row-body-tr" style="{bodyStyle}"><td nowrap="nowrap" colspan="{cols}" class="x-grid3-body-cell" tabIndex="0" hidefocus="on" ><div class="x-grid3-row-body">{body}</div></td></tr>'
						: ''), '</tbody></table>');
		ts.rowBody.disableFormats = true;
		ts.rowBody.compile();
	},

	getStyleRowHeight : function() {
		return Ext.isBorderBox
				? (this.rowHeight + this.borderHeight)
				: this.rowHeight;
	},

	getCalculatedRowHeight : function() {
		return this.rowHeight + this.borderHeight;
	},

	getVisibleRowCount : function() {
		var rh = this.getCalculatedRowHeight();
		var visibleHeight = this.scroller.dom.clientHeight;
		return (visibleHeight < 1) ? 0 : Math.ceil(visibleHeight / rh);
	},

	getVisibleRows : function() {
		var count = this.getVisibleRowCount();
		var sc = this.scroller.dom.scrollTop;
		var start = (sc == 0 ? 0 : Math.floor(sc
				/ this.getCalculatedRowHeight())
				- 1);
		return {
			first : Math.max(start, 0),
			last : Math.min(start + count + 2, this.ds.getCount() - 1)
		};
	},

	doRender : function(cs, rs, ds, startRow, colCount, stripe, onlyBody) {
		var ts = this.templates, ct = ts.cell, rt = ts.row, rb = ts.rowBody, last = colCount
				- 1;
		var rh = this.getStyleRowHeight();
		var vr = this.getVisibleRows();
		var tstyle = 'width:' + this.getTotalWidth() + ';height:' + rh + 'px;';
		// buffers
		var buf = [], cb, c, p = {}, rp = {
			tstyle : tstyle
		}, r;
		for (var j = 0, len = rs.length; j < len; j++) {
			r = rs[j];
			cb = [];
			var rowIndex = (j + startRow);
			var visible = rowIndex >= vr.first && rowIndex <= vr.last;
			if (visible) {
				for (var i = 0; i < colCount; i++) {
					c = cs[i];
					p.id = c.id;
					p.css = i == 0 ? 'x-grid3-cell-first ' : (i == last
							? 'x-grid3-cell-last '
							: '');
					p.attr = p.cellAttr = "";
					p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
					p.style = c.style;
					if (p.value == undefined || p.value === "") {
						p.value = "&#160;";
					}
					if (r.dirty && typeof r.modified[c.name] !== 'undefined') {
						p.css += ' x-grid3-dirty-cell';
					}
					cb[cb.length] = ct.apply(p);
				}
			}
			var alt = [];
			if (stripe && ((rowIndex + 1) % 2 == 0)) {
				alt[0] = "x-grid3-row-alt";
			}
			if (r.dirty) {
				alt[1] = " x-grid3-dirty-row";
			}
			rp.cols = colCount;
			if (this.getRowClass) {
				alt[2] = this.getRowClass(r, rowIndex, rp, ds);
			}
			rp.alt = alt.join(" ");
			rp.cells = cb.join("");
			buf[buf.length] = !visible ? ts.rowHolder.apply(rp) : (onlyBody
					? rb.apply(rp)
					: rt.apply(rp));
		}
		return buf.join("");
	},

	isRowRendered : function(index) {
		var row = this.getRow(index);
		return row && row.childNodes.length > 0;
	},

	syncScroll : function() {
		Ext.ux.grid.BufferView.superclass.syncScroll.apply(this, arguments);
		this.update();
	},

	// a (optionally) buffered method to update contents of gridview
	update : function() {
		if (this.scrollDelay) {
			if (!this.renderTask) {
				this.renderTask = new Ext.util.DelayedTask(this.doUpdate, this);
			}
			this.renderTask.delay(this.scrollDelay);
		} else {
			this.doUpdate();
		}
	},

	onRemove : function(ds, record, index, isUpdate) {
		Ext.ux.grid.BufferView.superclass.onRemove.apply(this, arguments);
		if (isUpdate !== true) {
			this.update();
		}
	},

	doUpdate : function() {
		if (this.getVisibleRowCount() > 0) {
			var g = this.grid, cm = g.colModel, ds = g.store;
			var cs = this.getColumnData();

			var vr = this.getVisibleRows();
			for (var i = vr.first; i <= vr.last; i++) {
				// if row is NOT rendered and is visible, render it
				if (!this.isRowRendered(i)) {
					var html = this.doRender(cs, [ds.getAt(i)], ds, i, cm
									.getColumnCount(), g.stripeRows, true);
					this.getRow(i).innerHTML = html;
				}
			}
			this.clean();
		}
	},

	// a buffered method to clean rows
	clean : function() {
		if (!this.cleanTask) {
			this.cleanTask = new Ext.util.DelayedTask(this.doClean, this);
		}
		this.cleanTask.delay(this.cleanDelay);
	},

	doClean : function() {
		if (this.getVisibleRowCount() > 0) {
			var vr = this.getVisibleRows();
			vr.first -= this.cacheSize;
			vr.last += this.cacheSize;

			var i = 0, rows = this.getRows();
			// if first is less than 0, all rows have been rendered
			// so lets clean the end...
			if (vr.first <= 0) {
				i = vr.last + 1;
			}
			for (var len = this.ds.getCount(); i < len; i++) {
				// if current row is outside of first and last and
				// has content, update the innerHTML to nothing
				if ((i < vr.first || i > vr.last) && rows[i].innerHTML) {
					rows[i].innerHTML = '';
				}
			}
		}
	},

	layout : function() {
		Ext.ux.grid.BufferView.superclass.layout.call(this);
		this.update();
	}
});

/**
 * 用户选择器
 * 
 * @param callback
 * @param isSingle
 * 
 * 
 */

var checkchange = function(node, checked) {
	// treeRight.root.setId(node.id);
	// treeRight.root.reload();
	var flg = false;
	var tksqbz = 1;
	// if (!node.isLeaf()) {
	if (checked) {
		node.parentNode.getUI().toggleCheck(true);
		node.eachChild(function(n) {
					if (n.getUI().isChecked()) {
						flg = true;
						return;
					}
				});
		if (flg == false) {
			node.eachChild(function(n) {
						if (n.getUI().isChecked() == false) {
							n.getUI().toggleCheck(true)
						}
					});
		}
		node.getUI().addClass('x-tree-node-checked');
	} else {
		node.parentNode.eachChild(function(n) {
					if (n.getUI().isChecked()) {
						flg = true;
						return;
					}
				})
		if (flg == false) {
			node.parentNode.getUI().toggleCheck(false)
		}
		node.getUI().removeClass('x-tree-node-checked');
		node.eachChild(function(n) {
					if (n.getUI().isChecked()) {
						flg = true;
						return;
					}
				});
		if (flg == true) {
			node.eachChild(function(n) {
						if (n.getUI().isChecked()) {
							n.getUI().toggleCheck(false)
						}
					});
		}
	}
};
var TyksUserSelector = {
	getView : function(callback, isSingle, bl) {
		wcbl = bl;
		var panel = this.initPanel(isSingle, wcbl);
		var window = new Ext.Window({
			title : '选择考试人员',
			width : 700,
			height : 420,
			layout : 'fit',
			items : [panel],
			modal : true,
			buttonAlign : 'center',
			buttons : [{
						text : '确认',
						iconCls : 'btn-save',
						scope : 'true',
						handler : function() {
							var grid = Ext.getCmp('contactGrid');
							var rows = grid.getSelectionModel().getSelections();
							var userIds = '';
							var fullnames = '';
							for (var i = 0; i < rows.length; i++) {

								if (i > 0) {
									userIds += ',';
									fullnames += ',';
								}
								userIds += rows[i].data.rybh;
								fullnames += rows[i].data.ryxm;
							}

							if (callback != null) {
								callback.call(this, userIds, fullnames);
							}
							window.close();
						}
					}, {
						text : '关闭',
						iconCls : 'btn-cancel',
						handler : function() {
							window.close();
						}
					}]
		});
		return window;
	},

	initPanel : function(isSingle, wcbl) {
		var store = new Ext.data.Store({
					proxy : new Ext.data.HttpProxy({
								url : _ctxPath + '/tyksUser4Select.do?wcl='
										+ wcbl
							}),
					reader : new Ext.data.JsonReader({
								root : 'list',
								totalProperty : 100,
								id : 'id',
								fields : ['ryxm', 'rybh', 'wcl', 'yymc', 'bmqc']
							}),
					remoteSort : true
				});
		store.setDefaultSort('id', 'desc');
		store.load({
					params : {
						tksqbz : 1,
						start : 0,
						limit : 12
					}
				});
		var sm = null;
		if (isSingle) {
			var sm = new Ext.grid.CheckboxSelectionModel({
						singleSelect : true
					});
		} else {
			sm = new Ext.grid.CheckboxSelectionModel();
		}
		var cm = new Ext.grid.ColumnModel({
					columns : [sm, new Ext.grid.RowNumberer(), {
						header : "姓名",
						dataIndex : 'ryxm',
						renderer : function(value, meta, record) {
							// var title=record.data.title;
							// if(title==1){
							return '<img src="' + _ctxPath
									+ '/images/flag/man.png"/>&nbsp;' + value;
							// }else{
							// return '<img
							// src="'+_ctxPath+'/images/flag/women.png"/>&nbsp;'+value;
							// }
						},
						width : 55
					}, {
						header : "完成率",
						dataIndex : 'wcl',
						width : 55
					}, {
						header : "专业",
						dataIndex : 'yymc',
						width : 50
					}, {
						header : "部门名称",
						dataIndex : 'bmqc',
						width : 250
					}],
					defaults : {
						sortable : true,
						menuDisabled : true,
						width : 120
					},
					listeners : {
						hiddenchange : function(cm, colIndex, hidden) {
							saveConfig(colIndex, hidden);
						}
					}
				});

		var treePanel = new Ext.tree.TreePanel({
					id : 'treePanels',
					title : '按部门分类',
					iconCls : 'dep-user',
					autoScroll : true,
					loader : new Ext.tree.TreeLoader({
								url : _ctxPath + '/system/genDeptTree.do?wcl='
										+ wcbl
							}),
					root : new Ext.tree.AsyncTreeNode({
								id : 34000000,
								expanded : true
							}),
					rootVisible : false,
					listeners : {
						'click' : this.clickNode,
						'checkchange' : function() {
							var selNodes = this.getChecked();
							var ids = [];
							Ext.each(selNodes, function(node) {
										ids.push(node.id);

									});
							Ext.getCmp('contactGrid').getStore().load({
										params : {
											'ids' : ids.join()
										}
									});
						}
					}
				});
		var yylxPanel = new Ext.tree.TreePanel({
					id : 'yylxPanel',
					title : '按学法类型分类 ',
					autoScroll : true,
					loader : new Ext.tree.TreeLoader({
								url : _ctxPath + '/genXtyylxTree.do'
							}),
					root : new Ext.tree.AsyncTreeNode({
								id : 40,
								expanded : true
							}),
					rootVisible : false,
					listeners : {
						'click' : this.clickYylxNode,
						'checkchange' : function() {
							var selNodes = this.getChecked();
							var yyids = [];
							Ext.each(selNodes, function(node) {
										yyids.push(node.id);

									});
							Ext.getCmp('contactGrid').getStore().load({
										params : {
											'yyids' : yyids.join()
										}
									});
						}
					}
				});

		var contactGrid = new Ext.grid.GridPanel({
			id : 'contactGrid',
			height : 345,
			store : store,
			shim : true,
			trackMouseOver : true,
			disableSelection : false,
			loadMask : true,
			cm : cm,
			sm : sm,
			viewConfig : {
				forceFit : true,
				enableRowBody : false,
				showPreview : false
			},
			tbar : new Ext.Toolbar({
						width : '100%',
						height : 30,
						items : ['-', {
							xtype : 'checkbox',
							id : 'tksqbz',
							fieldLabel : '已申请',
							checked : true,
							// name : 'fav-animal-dog',
							boxLabel : '已申请',
							listeners : {
								'check' : function(o, v) {
									tksqbz.value = (v == true ? 1 : "0");
									Ext.getCmp('contactGrid').getStore()
											.setBaseParam('tksqbz',
													(v == true ? 1 : "0"));
									Ext.getCmp('contactGrid').getStore().load();
								}
							}

						}, '-', '-', '-', '-', {
							xtype : 'tbtext',
							text : '已选择人数：'
						}, {
							xtype : 'numberfield',
							id : 'yxzrs',
							width : 50,
							minValue : 0
						}]
					}),
			view : new Ext.ux.grid.BufferView({
						// custom row height
						rowHeight : 25,
						// render rows as they come into viewable area.
						scrollDelay : false
					}),
			listeners : {
				rowclick : function(grid, rowidx, e) {
					Ext.getCmp('yxzrs').setValue(grid.getSelectionModel()
							.getCount());
				}
			}
				// ,
				// bbar : new Ext.PagingToolbar({
				// pageSize : 12,
				// store : store,
				// displayInfo : true,
				// displayMsg : '当前显示从{0}至{1}， 共{2}条记录',
				// emptyMsg : "当前没有记录"
				// })
		});

		var contactPanel = new Ext.Panel({
					id : 'contactPanel',
					width : 500,
					height : 400,
					layout : 'border',
					border : false,
					items : [{
								region : 'west',
								split : true,
								collapsible : true,
								width : 150,
								margins : '5 0 5 5',
								layout : 'accordion',
								items : [yylxPanel, treePanel]
							}, {
								region : 'center',
								autoScroll : true,
								margins : '5 0 5 5',
								width : 260,
								items : [contactGrid]
							}]
				});
		yylxPanel.expandAll();
		return contactPanel;
	},

	clickNode : function(node) {
		if (node != null) {
			var flg = node.getUI().isChecked();
			if (!flg) {
				node.getUI().toggleCheck(true);
			} else {
				node.getUI().toggleCheck(false);
			}
			var selNodes = this.getChecked();
			var ids = [];
			Ext.each(selNodes, function(node) {
						ids.push(node.id);

					});
			var users = Ext.getCmp('contactGrid');
			var store = users.getStore();
			store.proxy.conn.url = _ctxPath + '/tyksUser4Select.do?wcl=' + wcbl;
			store.baseParams = {
				tksqbz : tksqbz.value,
				ids : ids.join()
			};
			store.load({
						params : {
							start : 0,
							limit : 12
						}
					});
		}
	},
	clickYylxNode : function(node) {
		if (node != null) {
			var flg = node.getUI().isChecked();
			if (!flg) {
				node.getUI().toggleCheck(true);
			} else {
				node.getUI().toggleCheck(false);
			}
			var selNodes = this.getChecked();
			var yyids = [];
			Ext.each(selNodes, function(node) {
						yyids.push(node.id);

					});
			var users = Ext.getCmp('contactGrid');
			var store = users.getStore();
			store.proxy.conn.url = _ctxPath + '/tyksUser4Select.do?wcl=' + wcbl;
			store.baseParams = {
				tksqbz : tksqbz.value,
				yyids : yyids.join()
			};
			store.load({
						params : {
							start : 0,
							limit : 12
						}
					});
		}
	}
};
